package com.example.hellomap;

import java.util.ArrayList;
import java.util.Calendar;

import android.content.Context;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.hellomap.model.Authorizor;
import com.example.hellomap.model.Date;
import com.example.hellomap.model.Places_mock;
import com.example.hellomap.rest.*;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * @author Alle
 * A fő osztályunk, ebből kell meghívni minden más Activityt
 */
public class MainActivity extends FragmentActivity {    
	
	MyGoogleMap mymap;
	MyLocationListener myLocListener;
	
	//
	private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    //
    private Button authLogin;
    private Button authCancel;
    private PopupWindow pwindo;
    private EditText authUser;
    private EditText authPass;
    //
    private Date date;
    private Button datepicker;
    //
    private Button eventOK;
    private Button eventCancel;
    private AutoCompleteTextView eventPlace;

	public MyGoogleMap getMymap() {
		return mymap;
	}

	public MyLocationListener getMyLocListener() {
		return myLocListener;
	}

	public DrawerLayout getmDrawerLayout() {
		return mDrawerLayout;
	}

	public ListView getmDrawerList() {
		return mDrawerList;
	}

	@Override
    public void onCreate(Bundle savedInstanceState) {
		System.out.println("valami");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);  
        StrictMode.ThreadPolicy policy = 
                new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        myLocListener = new MyLocationListener(this);
        myLocListener.initLocation();	
        
        mymap = new MyGoogleMap(this, myLocListener);        
        mymap.setUpMapIfNeeded(((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_layout)).getMap()); 
        mymap.initMap();    
        
        setUpDrawer();
                
        setupDateButton();
        //users proba =new users("Bendzsi", "tequila", "mex@mex.me");
        //ServerInterface.post("users", proba); //TODO: megírni a másik 3ra is
        ServerInterface.get("users");
        
        getPlaces();
        
    }	// end of onCreate()

	/**
	 * @author Alle
	 * Baloldalról kihúzható menü:
	 */
	private void setUpDrawer() {
		
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerLayout.setDrawerListener(mDrawerListener);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);
		mDrawerList.setAdapter(new MyDrawerAdapter(this, MyDrawerAdapter.getDefaultElementsList(this)));
		mDrawerList.setOnItemClickListener(mDrawerItemClickedListener);
		findViewById(R.id.map_layout).setOnTouchListener(touchListener);

	}
	
	private void setupDateButton(){
		date = new Date();
		
        View layout = findViewById(R.id.map_layout);
        datepicker = (Button) layout.findViewById(R.id.date_picker);
        datepicker.setOnClickListener(dpDateClickedListener);
        updateDateButton();
	}
	
	private void updateDateButton(){
        datepicker.setText(date.getYear() + "-" + (date.getMonth()+1) + "-" + date.getDay());		
	}
	
	private void getPlaces(){
		BitmapDescriptor bitmapDsc = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE);
		/*System.out.println(Places_mock.demoPlaces[0].getFrom() + " " + date);
    	for(int i = 0; i < Places_mock.demoPlaces.length; ++i){
    		if(Places_mock.demoPlaces[i].getFrom().equals(date)){
	    		LatLng ll = new LatLng(Places_mock.demoPlaces[i].getLat(), Places_mock.demoPlaces[i].getLon());
		    	mymap.getMyGoogleMap().addMarker(new MarkerOptions()
		    			.title(Places_mock.demoPlaces[i].getName())
		    			.position(ll)
		    			.icon(bitmapDsc));
    		}
    	}*/
		mymap.getMyGoogleMap().clear();
    	ArrayList<Object>  events = ServerInterface.get("events");
    	for(Object o: events){
    		events e = (events) o;
    		places p = (places) ServerInterface.get("places/"+e.getPlace()).get(0);
    		
    		Date d = new Date(e.getFrom());
    		if(date.equals(d)){
    			LatLng ll = new LatLng(p.getLat(), p.getLon());
		    	mymap.getMyGoogleMap().addMarker(new MarkerOptions()
		    			.title(e.getName())
		    			.position(ll)
		    			.icon(bitmapDsc));
    		}
    	}
	}
	
	private OnTouchListener touchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if(event.getAction() == MotionEvent.ACTION_DOWN){
                mDrawerLayout.openDrawer(mDrawerList);
                return false;
            }
            return false;
		}
    };
    
    private OnItemClickListener mDrawerItemClickedListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            
            android.support.v4.app.Fragment fragment = null;
            //Kivalasztott elem
            switch(position){
                case 0:
                	createAuthPopup();
                break;
                case 1:
                    fragment = new UjFragment();
                    if(Authorizor.getUser() == null){
                    	Toast.makeText(MainActivity.this, "Nincs bejelentkezve", Toast.LENGTH_LONG).show();
                    } else {
                    	createEventPopup();
                    }
                break;
                
                default:
                return;
            }
            
            if(fragment != null){
            	getSupportFragmentManager().beginTransaction().replace(R.id.map_layout, fragment).commit();
            }
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    };
    
 // Catch the events related to the drawer to arrange views according to this action if necessary...
 	private DrawerListener mDrawerListener = new DrawerListener() {

 		@Override
 		public void onDrawerStateChanged(int status) {

 		}

 		@Override
 		public void onDrawerSlide(View view, float slideArg) {
 			
 		}

 		@Override
 		public void onDrawerOpened(View view) {
 		}

 		@Override
 		public void onDrawerClosed(View view) {
 		}
 	};

	@Override
    protected void onResume() {
        super.onResume();
        mymap.setUpMapIfNeeded(((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_layout)).getMap());    
        mymap.initMap();       
        myLocListener.requestLocationUpdates();
    }
    
	@Override
	protected void onPause() {
		super.onPause();
		myLocListener.removeUpdates();
	}
    
    /**  
     * @author Alle  
     * A telefon 'fizikai' MENU gombára kattintáskor előugró panel. 
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {				
    	
    	super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate( R.menu.activity_menu, menu );
        return true;
    }      

    /**
     * @author Csicsi
     */
    private void createAuthPopup(){
    	try {
    		LayoutInflater inflater = (LayoutInflater) MainActivity.this
    		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		View layout = inflater.inflate(R.layout.auth_layout,
    		(ViewGroup) findViewById(R.id.auth_popup));
    		pwindo = new PopupWindow(layout, 300, 280, true);
    		pwindo.showAtLocation(layout, Gravity.CENTER, 0, -100);
    		
    		authLogin = (Button) layout.findViewById(R.id.auth_ok);
    		authLogin.setOnClickListener(aLoginClickedListener);
    		
    		authCancel = (Button) layout.findViewById(R.id.auth_cancel);
    		authCancel.setOnClickListener(aCancelClickedListener);
    		
    		authUser = (EditText) layout.findViewById(R.id.user_text);
    		authPass = (EditText) layout.findViewById(R.id.pass_text);

		} catch (Exception e) {
			e.printStackTrace();
		}
    }

    /**
     * @author Csicsi
     */
    private void createEventPopup(){
    	try {
    		LayoutInflater inflater = (LayoutInflater) MainActivity.this
    		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		View layout = inflater.inflate(R.layout.event_layout,
    		(ViewGroup) findViewById(R.id.event_popup));
    		pwindo = new PopupWindow(layout, 400, 500, true);
    		pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
    		
    		eventOK = (Button) layout.findViewById(R.id.event_ok);
    		eventOK.setOnClickListener(eOKClickedListener);
    		
    		eventCancel = (Button) layout.findViewById(R.id.event_cancel);
    		eventCancel.setOnClickListener(eCancelClickedListener);
    		
    		/*eventPlace = (AutoCompleteTextView) layout.findViewById(R.id.ac_event_loc);
    		ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,countries);
    		eventPlace.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, item));*/
    		
    		//((Button) layout.findViewById(R.id.event_fromdate)).setOnClickListener(dpDateClickedListener);

		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    /**
     * @author Csicsi
     * a bejelentkezes megse gombjanak listenerje
     */
    private OnClickListener aCancelClickedListener = new OnClickListener(){
    	
		@Override
		public void onClick(View v) {
			pwindo.dismiss();
			mDrawerLayout.openDrawer(mDrawerList);
		}
    };
    
    /**
     * @author Csicsi
     * a bejelentkezes ok gombjanak listenerje
     */
    private OnClickListener aLoginClickedListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			Toast.makeText(MainActivity.this, "Belépés ellenőrzőse", Toast.LENGTH_SHORT).show();
			String user = authUser.getText().toString();
			String pass = authPass.getText().toString();
			Authorizor.checkData(user, pass);
			String errors = Authorizor.getErrors();
			if(errors.length() > 0){
				Toast.makeText(MainActivity.this, errors, Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(MainActivity.this, Authorizor.getUser() + " bejelentkezve", Toast.LENGTH_LONG).show();
				pwindo.dismiss();
			}
		}
    	
    };
    
    private OnClickListener eOKClickedListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Esem�ny felv�tele
			pwindo.dismiss();
		}
	};
	
	private OnClickListener eCancelClickedListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			pwindo.dismiss();
		}
	};
    
    /**
     * @author Csicsi
     * a datepicker kezelogombjanak listenerje
     */
    private OnClickListener dpDateClickedListener = new OnClickListener(){

		@Override
		public void onClick(View v) {
			DialogFragment newFragment = new MyDatePickerFragment();
            newFragment.show(getSupportFragmentManager(), "datePicker");
		}
    	
    };
    
    public void setDate(int y, int m, int d){
    	if(date.getYear() != y || date.getMonth() != m || date.getDay() != d){
	    	date.setYear(y);
	    	date.setMonth(m);
	    	date.setDay(d);
	    	Toast.makeText(MainActivity.this, date.getYear() + "-" + (date.getMonth()+1) + "-" + date.getDay(), Toast.LENGTH_LONG).show();
	    	updateDateButton();
	    	//TODO: be�ll�tott d�tumnak megfelel� esem�nyek lek�r�se, az aktu�lis poz�ci� k�r�l
	    	getPlaces();
    	}
    }

	public Date getDate() {
		return date;
	}
    
    private String[] getIds(ArrayList<Object> list, String type){
		ArrayList<String> temp = new ArrayList<String>();
    	try {
			if( type.equals("places") ){
				for(Object o: list){
					places p = (places) o;
					temp.add(p.getId());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	String[] ret = (String[]) temp.toArray();
    	return ret;    	
    }
}




